import Taro, { useState, useEffect, request } from '@tarojs/taro';
import { View } from '@tarojs/components';
import { AtTabBar, AtMessage } from 'taro-ui';
import { TabItem } from 'taro-ui/@types/tab-bar';
import './index.less';
import Home from '../home/index';
import My from '../my/index';
import Found from '../found/index';
import Position from '../../common/position/getPosition';
import Config from '../../config/index';
import { WeacherInter } from '../../model/index';

const Index = () => {
  const [current, setCurrent] = useState<number>(0);
  const [weacher, setWeacher] = useState<WeacherInter>({
    city: '',
    province: '',
    reporttime: '',
    casts: {
      daytemp: '',
      dayweather: '',
    },
  });
  const [tabList, setTabList] = useState<TabItem[]>([
    { title: '首页', text: '0', iconPrefixClass: 'icon', iconType: 'shouyeshouye' },
    { title: '发现', iconPrefixClass: 'icon', iconType: 'wode' },
    { title: '我的', iconPrefixClass: 'icon', iconType: 'wode' },
  ]);
  const handleClick = (value: number) => {
    setCurrent(value);
  };
  useEffect(() => {
    getPositionInfo();
  }, []);
  const getPositionInfo = () => {
    // @ts-ignore
    Position().then((res: any) => {
      if (res && res.city) {
        // 获取天气情况
        request({
          url: `${Config.gdUrl}v3/weather/weatherInfo?key=e911e1638acf1d4d772d3106e5bf4708&city=${res.city}&extensions=all`,
          method: 'GET',
          success: result => {
            console.log(result);
            if (result.statusCode === 200) {
              const data = result.data.forecasts[0];
              setWeacher({
                city: data.city,
                province: data.province,
                reporttime: data.reporttime,
                casts: data.casts[0],
              });
              Taro.atMessage({
                message: '天气信息加载成功!',
                type: 'success',
              });
            }
          },
          fail: err => {
            console.log(err);
          },
        });
      }
    });
  };
  return (
    <View className="index">
      {current === 0 ? <Home refresh={() => getPositionInfo()} weacher={weacher} /> : null}
      {current === 1 ? <Found /> : null}
      {current === 2 ? <My /> : null}
      <AtTabBar fixed tabList={tabList} current={current} onClick={handleClick} />
      {/* 顶部消息通知 */}
      <AtMessage />
    </View>
  );
};
Index.config = {
  navigationBarTitleText: '首页',
};
export default Index;
